<script>
    import Device from "../../../components/Device/Device.svelte";
    import { devices } from "../stores";
    import { onDestroy, onMount } from "svelte";

    let width = 837,
        height = 530;
    let clientWidth = 837,
        clientHeight = 530;

    function getX(x) {
        if (clientWidth / clientHeight > width / height) {
            const rate = clientHeight / height;
            const offset = (clientWidth - width * rate) / 2;
            return x * rate + offset;
        } else {
            const rate = clientWidth / width;
            const offset = (clientHeight - height * rate) / 2;
            return x * rate;
        }
    }

    function getY(y) {
        if (clientWidth / clientHeight > width / height) {
            const rate = clientHeight / height;
            const offset = (clientWidth - width * rate) / 2;
            return y * rate;
        } else {
            const rate = clientWidth / width;
            const offset = (clientHeight - height * rate) / 2;
            return y * rate + offset;
        }
    }

    let devicesRaw;
    let devicesData;
    const unsubscribe = devices.subscribe((data) => {
        devicesRaw = data;
        devicesData = getDeviceData(devicesRaw);
    });

    function getDeviceData(devices) {
        return devices.map((d) => ({
            ...d,
            location: {
                left: getX(d.location.left),
                top: getY(d.location.top),
            },
        }));
    }

    onMount(() => {
        const urlParams = new URLSearchParams(window.location.search);
        const type = urlParams.get("type") || 1;
        devices.get(type);
    });

    onDestroy(unsubscribe);

    function onResize() {
        if (devicesRaw) {
            devicesData = getDeviceData(devicesRaw);
        }
    }
</script>

<svelte:window on:resize={onResize} />
<div class="h-full bg relative" bind:clientWidth bind:clientHeight>
    {#each devicesData as device}
        <Device
            label={device.label}
            type={device.type}
            top={device.location.top}
            left={device.location.left}
            active={device.active}
            icon={device.filePath}
            on:toggle={() => {
                const urlParams = new URLSearchParams(window.location.search);
                const type = urlParams.get("type") || 1;
                devices.select(type, device.id, device.type);
            }}
        />
    {/each}
</div>

<style>
    .bg {
        background-image: url("./center-bottom.png");
        /*width: 837px;*/
        /*height: 530px;*/
        @apply bg-center bg-no-repeat bg-contain;
    }
</style>
